package com.roadjava.rbac.util;

import cn.hutool.core.collection.CollUtil;
import com.roadjava.rbac.bean.vo.SortableTreeNode;
import com.roadjava.rbac.constants.CommonConstants;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class SortableTreeUtil {
    public static <T extends SortableTreeNode<T>> List<T> buildTree(Collection<T> nodeList) {
        List<T> rootNodeList = new ArrayList<>();
        Map<Long,T> map = nodeList.stream()
                .collect(Collectors.toMap(T::getId, Function.identity(), (a1, a2) -> a2));
        for (T node : nodeList) {
            Long parentId = node.getParentId();
            if (CommonConstants.TOP_PARENT_ID.equals(parentId)) {
                // 根节点直接放入集合中
                rootNodeList.add(node);
            }else {
                T nodeParent = map.get(parentId);
                nodeParent.addChild(node);
            }
        }
        sort(rootNodeList);
        return rootNodeList;
    }

    private static <T extends SortableTreeNode<T>> void sort(List<T> nodeList) {
        nodeList.sort(Comparator.comparingInt(SortableTreeNode::getOrderNo));
        for (T node : nodeList) {
            List<T> children = node.getChildren();
            if (CollUtil.isEmpty(children)) {
                continue;
            }
            sort(children);
        }
    }
}
